<template>
  <div style="">
    <Header :left="true" leftText="返回" title="订单切换"> </Header>
    <NoticeBar color="#1989fa" background="#ecf9ff" style="margin-top: 5px; font-size: 15px; font-weight: bold"
      :left-icon="showicon()" :text="showText()"></NoticeBar>
    <div v-if="producing">
      <van-form :style="autoHeight" @submit="onSubmit">
        <van-field readonly class="formstyle" v-model="machineID" name="设备条码" label="设备条码" />
        <van-field readonly class="formstyle" v-model="pOrderID" name="工单条码" label="工单条码" />
        <van-field readonly class="formstyle" v-model="materialid" name="订单物料号" label="订单物料号" />
        <van-field readonly class="formstyle" v-model="materialname" name="订单物料描述" label="订单物料描述" />
        <van-field readonly class="formstyle" v-model="porderamt" name="订单数量" label="订单数量" />

        <van-field readonly class="formstyle" v-model="shouldproductionamount" name="应生产数量" label="应生产数量" />

        <van-field readonly class="formstyle" v-model="EnterAmount" name="已生产数量" label="已生产数量" />

        <van-field readonly class="formstyle" v-model="enterbegindatetime" name="生产开始时间" label="生产开始时间" />

        <van-field readonly class="formstyle" :value="form2.beginDatetime" name="生产结束时间" label="生产结束时间" />

        <div style="margin: 16px">
          <van-row class="button" gutter="3">
            <van-col span="12">
              <!-- <van-button :block="true" class="buttonColor2" type="warning" color="#f58220" round text="暂停生产"
                v-if="pauseP" @click="pauseProduction" /> -->
              <van-button :block="true" class="buttonColor2" type="primary" round text="继续生产" v-if="continueP"
                @click="continueProduction" />


            </van-col>
            <van-col span="12"><van-button :block="true" round class="buttonColor" type="danger" color="#d71345"
                text="生产结束" @click="stopProduction" /></van-col>
          </van-row>
        </div>
      </van-form>
    </div>
    <div v-if="notProduction">
      <van-cell-group>
        <van-field required v-model="machineID" label="设备条码" class="formstyle" readonly right-icon="scan"
          placeholder="点击扫描设备条码" @click="showScanner" />
        <van-field required v-model="form2.pOrderID" label="工单条码" class="formstyle" readonly right-icon="scan"
          placeholder="点击扫描工单条码" @click="showOrderScanner" />
      </van-cell-group>
      <van-form :style="autoHeight" @submit="onSubmit">
        <van-field readonly class="formstyle" v-model="form2.materialid" name="订单物料号" label="订单物料号" />
        <van-field readonly class="formstyle" v-model="form2.materialname" name="订单物料描述" label="订单物料描述" />
        <van-field readonly class="formstyle" v-model="form2.porderamt" name="订单数量" label="订单数量" />

        <van-field readonly class="formstyle" v-model="form2.shouldproductionamount" name="应生产数量" label="应生产数量" />

        <van-field readonly class="formstyle" :value="form2.beginDatetime" name="生产开始时间" label="生产开始时间" />

        <div style="margin: 16px">
          <van-button :block="true" class="buttonColor2" type="primary" round color="#138087" @click="saveproductionorder"
            text="开始生产" />
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import {
  Col,
  Row,
  Form,
  Cell,
  Icon,
  Field,
  NumberKeyboard,
  Image as VanImage,
  Picker,
  popup,
  SubmitBar,
  Button,
  Loading,
  Overlay,
  Dialog,
  Toast,
  NoticeBar,
  Tag,
  DatetimePicker,
  ImagePreview,
  CellGroup,
  Uploader,
  Cascader,
  Calendar,
  RadioGroup,
  Radio,
  Divider,
  Stepper,
  AddressList,
  Checkbox,
  CheckboxGroup,
} from "vant";

import "vue-easytable/libs/themes-base/index.css";
import { VTable } from "vue-easytable";
import { _httpClient } from "@/libs/apisie";
import { getToken, getBaseApiFrefix } from "@/libs/auth";
import Header from "@/components/header.vue";
import { storage } from "@/libs/utils";

Vue.use(Form);
Vue.use(Field);
Vue.use(Overlay);
Vue.use(Loading);
Vue.use(Picker);
Vue.use(popup);
Vue.use(SubmitBar);
Vue.use(VanImage);
Vue.use(DatetimePicker);
Vue.use(Cascader);
Vue.use(Calendar);
Vue.use(Cell);
Vue.use(RadioGroup);
Vue.use(Radio);
Vue.use(Divider);
Vue.use(Stepper);
Vue.use(Button);
Vue.use(AddressList);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Col);
Vue.use(Row);

export default {
  name: "switchorder",
  components: {
    Form,
    Row,
    Col,
    Button,
    Header,
    Form,
    Cell,
    Icon,
    Field,
    NumberKeyboard,
    Dialog,
    Toast,
    NoticeBar,
    Row,
    Tag,
    popup,
    DatetimePicker,
    ImagePreview,
    CellGroup,
    Uploader,
    Col,
    Calendar,
    Cascader,
    Picker,
    RadioGroup,
    Radio,
    Divider,
    Stepper,
    VTable,
    AddressList,
    Checkbox,
    CheckboxGroup,
  },
  data() {
    return {
      //设备号
      machineID: "",
      //工单号
      pOrderID: "",
      materialid: "",
      materialname: "",
      porderamt: "",
      shouldproductionamount: "",
      beginDatetime: "",
      enterbegindatetime: "",
      materialidNew: "",
      materialnameNew: "",
      shouldproductionamountNew: "",
      EnterAmount: "",
      //生产状态
      status: "",
      notProduction: false,
      producing: false,
      continueP: false,
      pauseP: false,
      form2: {
        pOrderID: "",
        materialid: "",
        materialname: "",
        porderamt: "",
        shouldproductionamount: "",
        beginDatetime: "",
      }
    };
  },

  created: function () {
    this.user = JSON.parse(storage.get("user"));
    var time = new Date();
    this.form2.beginDatetime =
      time.getFullYear() +
      "-" +
      (time.getMonth() + 1).toString().padStart(2, 0) +
      "-" +
      time.getDate().toString().padStart(2, 0) +
      " " +
      time.getHours().toString().padStart(2, 0) +
      ":" +
      time.getMinutes().toString().padStart(2, 0) +
      ":" +
      time.getSeconds().toString().padStart(2, 0);
    this.showScanner();
  },
  mounted() {
    //this.getcurrentorder();
    setInterval(this.getAmount, 5000);
  },
  destroyed() {
    this.reset();
  },
  methods: {
    showicon() {
      let status = this.status.trim();
      if (status === "正在生产") {
        return "assets/greencircle.png";
      } else if (status === "暂停生产") {
        return "assets/yellowcircle.png";
      } else
        return "assets/greycricle.png";
    },
    showText() {
      let status = this.status.trim();
      if (status === "正在生产") {
        return "正在生产-生产订单信息";
      } else if (status === "暂停生产") {
        return "暂停生产-生产订单信息";
      } else {
        return "当前设备暂无正在生产订单";
      }
    },
    checkButton(status) {
      if (status.trim() === "正在生产") {
        this.pauseP = true;
        this.continueP = false;
      } else if (status.trim() === "暂停生产") {
        this.continueP = true;
        this.pauseP = false;
      }
    },
    //点击暂停生产按钮 
    pauseProduction() {
      var pauseStatus = '1';
      this.operateCurrentOrder(pauseStatus);
    },
    //点击继续生产按钮
    continueProduction() {
      var pauseStatus = '0';
      this.operateCurrentOrder(pauseStatus);
    },
    //点击生产结束按钮
    stopProduction() {

      let _that=this

      api.confirm( {
        title: '',
        msg: "是否确认结束？",
        buttons: [ '确定', '取消' ]
      }, function ( ret, err ) {
        var index = ret.buttonIndex;
        if ( index == 1 ) {
           _that.CompleteProduce();
        }
      } )
      
    },
    //打开扫描
    showScanner() {
      let _this = this;
      var FNScanner = _this.$ac.require("FNScanner");
      FNScanner.openScanner(
        {
          autorotation: true,
        },
        function (ret, err) {
          if (ret) {
            if (ret.eventType == "success" && ret.content != "") {
              _this.machineID = ret.content;
              _this.getcurrentorder(_this.machineID);
            } else if (ret.eventType == "cancel") {
              _this.$ac.closeWin();
            }
          } else {
            alert(JSON.stringify(err));
            _this.$ac.closeWin();
          }
        }
      );
    },
    //打开扫描工艺单
    showOrderScanner() {
      let _this = this;
      var FNScanner = _this.$ac.require("FNScanner");
      FNScanner.openScanner(
        {
          autorotation: true,
        },
        function (ret, err) {
          if (ret) {
            if (ret.eventType == "success" && ret.content != "") {
              //_this.form2.pOrderID =  "000" + "190042740";
              _this.form2.pOrderID = ret.content;
              _this.getproductionorder(_this.form2.pOrderID);
            }
          } else {
            alert(JSON.stringify(err));
          }
        }
      );
    },
    //获取⽣产线正在⽣产订单
    async getcurrentorder(machineID) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() +
          "/MachineCurrentPOrder/GetCurrentOrder?MachineID=" + machineID,
        );
        if (res.HttpCode === "200" && res.Total > 0) {
          Toast.clear();
          _this.pOrderID = res.Data[0].POrderID;
          _this.materialid = res.Data[0].MaterailID;
          _this.materialname = res.Data[0].MaterailName;
          _this.porderamt = res.Data[0].POrderAmt;
          _this.shouldproductionamount = res.Data[0].ShouldProductionAmount;
          _this.enterbegindatetime = res.Data[0].EnterBeginDatetime;
          _this.EnterAmount = res.Data[0].OutAmountGood;
          _this.status = res.Data[0].ProductionStatus;
          _this.checkButton(_this.status);
          _this.producing = true;
          _this.notProduction = false;
        } else {
          Toast.clear();
          _this.status = "结束生产";
          _this.notProduction = true;
          _this.producing = false;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //获取⽣产线正在⽣产订单
    async getAmount() {
      let _this = this;
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() +
          "/MachineCurrentPOrder/GetCurrentOrder?MachineID=" + _this.machineID,
        );
        if (res.HttpCode === "200" && res.Total > 0) {
          _this.EnterAmount = res.Data[0].OutAmountGood;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    //暂停正在⽣产订单或恢复正在⽣产订单
    async operateCurrentOrder(status) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() +
          "/MachineCurrentPOrder/SuspendProduce?MachineID=" + _this.machineID + "&ProductionStatus=" + status,
        );
        if (res.HttpCode === "200") {
          Toast.clear();
          Toast.success("操作成功");
          _this.getcurrentorder(_this.machineID);
        } else {
          Toast.fail(res.errMessage);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //结束生产
    async CompleteProduce() {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() +
          "/MachineCurrentPOrder/CompleteProduce?MachineID=" + _this.machineID,
        );
        if (res.HttpCode === "200") {
          Toast.clear();
          Toast.success("操作成功");
          _this.getcurrentorder(_this.machineIDd);
        } else {
          Toast.fail(res.errMessage);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //根据工艺单号获取获取订单信息
    async getproductionorder(pOrderID) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() +
          "/ProductionOrder/GetList?POrderID=" + pOrderID,
        );
        if (res.Message == null) {
          Toast.clear();
          _this.form2.materialid = res.Data[0].MaterialID,
            _this.form2.materialname = res.Data[0].MaterialName,
            _this.form2.porderamt = res.Data[0].CompleteAmount,
            _this.form2.shouldproductionamount = res.Data[0].POrderAmount
        } else {
          Toast.fail("未查询到订单数据");
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //开始生产
    async saveproductionorder() {
      let _this = this;
      let pOrder = _this.form2.pOrderID.trim();
      let PLineID = _this.machineID;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "Loading...",
      });
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() +
          "/MachineCurrentPOrder/CreateProductionOrder?PLineID=" + PLineID + "&POrderID=" + pOrder,
        );
        if (res.Data != null) {
          Toast.clear();
          Toast.success("开始生产")
          Toast.success(res.Message);
          _this.getcurrentorder(_this.machineID);
        } else {
          Toast.fail(res.Message);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    reset() {
      //设备号
      this.machineID = "";
      //工单号
      this.pOrderID = "";
      this.materialid = "";
      this.materialname = "";
      this.porderamt = "";
      this.shouldproductionamount = "";
      this.beginDatetime = "";
      this.enterbegindatetime = "";
      this.materialidNew = "";
      this.materialnameNew = "";
      this.shouldproductionamountNew = "";
      this.EnterAmount = "";
      //生产状态
      this.status = "";
      this.notProduction = false;
      this.producing = false;
      this.continueP = false;
      this.pauseP = false;
      this.form2 = {
        pOrderID: "",
        materialid: "",
        materialname: "",
        porderamt: "",
        shouldproductionamount: "",
        beginDatetime: "",
      }
    }
  },
};
</script>

<style>
body {
  background-color: white;
}

.table-title-class {
  background-color: #304156;
  color: #fff;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.buttongroup {
  float: right;
  margin-right: 10px;
  margin-top: 10px;
  margin-bottom: 20px;
}

.container.dwo {
  display: flex;
  justify-content: center;
  align-items: center;
}

.buttonLeft {
  position: fixed;
  bottom: 8px;
  float: left;
  width: 49%;
}

.formstyle {
  margin-top: 8px;
  font-size: 15px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.radioteam {
  display: flex;
  align-items: center;
  padding-left: 13px;
  margin-top: 10px;
  margin-left: 34px;
  margin-bottom: 10px;
}

.buttonRight {
  position: fixed;
  bottom: 8px;
  float: right;
  left: 51%;
  width: 49%;
  background-color: #f22028;
  border-color: #f22028;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 50%;
  bottom: 3rem;
  overflow: scroll;
  right: 10px;
  width: 100%;
  z-index: 1;
}

.message {
  font-size: 15px;
  margin-top: 5px;
  margin-left: -10px;
  font-weight: bold;
}

.mg5 {
  margin-right: 5px;
}

.tag_margin {
  margin: 2px 5px;
}

.card_under {
  height: 100%;
  width: 100%;
  margin: auto;
  background: #ffffff;
  border-radius: 25px;
  box-shadow: 0 0px 0px rgba(0, 0, 0, 0.3);
}

.card_icon {
  text-align: center;
  /* position: absolute; */
  height: 8rem;
  width: 80%;
  margin: 12% 10%;
  background: rgba(35, 180, 237, 1);
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.text {
  font-size: 18px;
  color: #4e4a67;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.text_small {
  font-size: 16px;
  color: red;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 700;
}

.text_scan {
  font-size: 16px;
  color: #4e4a67;
  margin: auto auto auto 20px;
  line-height: 1.5em;
  text-align: justify;
}

.divStyle {
  margin-left: 3px;
  margin-right: 3px;
}
</style>
